package com.itcat.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.itcat.mysql.pojo.UmsAdmin;
import com.itcat.mysql.pojo.UmsResource;
import com.itcat.service.AdminCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.List;

/**
 * [一句话描述该类的功能]
 *
 * @author : [Cr Mr]
 * @version : [v1.0]
 * @date : [2022/3/30 16:28]
 */
@Component
@Service
public class AdminCacheServiceImpl implements AdminCacheService {

    @Value("${mall.redis.key.admin}")
    private String REDIS_KEY_ADMIN;


    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public UmsAdmin getAdmin(String username) {
        String key = REDIS_KEY_ADMIN + ":" + username;
        return JSON.parseObject(redisTemplate.opsForValue().get(key), UmsAdmin.class);
    }

    @Override
    public void setAdmin(UmsAdmin admin) {
        String key = REDIS_KEY_ADMIN + ':' + admin.getUsername();
        redisTemplate.opsForValue().set(key, JSON.toJSONString(admin), Duration.ofMillis(30));
    }

    @Override
    public List<UmsResource> getResourceList(Long adminId) {
        String key = REDIS_KEY_ADMIN + ":" + adminId;
        return JSONArray.parseArray(redisTemplate.opsForValue().get(key), UmsResource.class);
    }

    @Override
    public void setResourceList(Long adminId, List<UmsResource> resourceList) {
        String key = REDIS_KEY_ADMIN + ":" + adminId;
        redisTemplate.opsForValue().set(key, JSONArray.toJSONString(resourceList), Duration.ofMillis(30));
    }

    @Override
    public void removeAdmin(UmsAdmin admin) {
        String key1 = REDIS_KEY_ADMIN + ":" + admin.getId();
        String key2 = REDIS_KEY_ADMIN + ":" + admin.getUsername();
        redisTemplate.delete(key1);
        redisTemplate.delete(key2);
    }


}
